// pages/category/index.js
import { request } from "../../request/index.js"

Page({
    data: {
        leftMenuList: [],
        rightContent: [],
        activeIndex: 0,
        scrollToTop:0,
    },
    // 返回接口数据
    Cates: [],
    onLoad(options) {
        // 缓存较大的数据
        const Cates = wx.getStorageSync('cates')
        if (!Cates) {
            this.getCateList();
        } else if (Date.now() - Cates.time > 1000 * 300) {
            // 过期，重新发送请求
            this.getCateList();
        } else {
            this.Cates = Cates.data
            let leftMenuList = this.Cates.map(item => {
                return item.cat_name
            });
            let rightContent = this.Cates[0].children;
            this.setData({
                leftMenuList,
                rightContent
            })
        }
    },
    async getCateList() {
        const res = (await request({ url: '/categories' })).data
        this.Cates = res.message
        wx.setStorageSync('cates', { time: Date.now(), data: this.Cates })
        let leftMenuList = this.Cates.map(item => {
            return item.cat_name
        });
        let rightContent = this.Cates[0].children;
        this.setData({
            leftMenuList,
            rightContent
        })
    },
    menuItemClick(e) {
        let { index } = e.currentTarget.dataset
        let rightContent = this.Cates[index].children;
        this.setData({
            activeIndex: index,
            rightContent,
            scrollToTop:0,
        })
    }
})